package com.example.tliaswebmanagement.AOP;

import com.example.tliaswebmanagement.mapper.OperateLogMapper;
import com.example.tliaswebmanagement.pojo.OperateLog;
import com.example.tliaswebmanagement.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperationLogAspect {
    private final OperateLogMapper operateLogMapper;

    public OperationLogAspect(OperateLogMapper operateLogMapper) {
        this.operateLogMapper = operateLogMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Around("@annotation(com.example.tliaswebmanagement.anno.Log)")
    public Object logOperation(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        // 开始时间
        long beginTime = System.currentTimeMillis();

        // 切入点
        Object result = proceedingJoinPoint.proceed();

        // 结束时间
        long endTime = System.currentTimeMillis();
        // 计算耗时
        long costTime = endTime - beginTime;

        // 封装日志信息
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(getCurrentUserId());  // 获取当前用户 ID
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(proceedingJoinPoint.getClass().getName());
        operateLog.setMethodName(proceedingJoinPoint.getSignature().getName());
        operateLog.setMethodParams(Arrays.toString(proceedingJoinPoint.getArgs()));
        operateLog.setReturnValue(result != null ? result.toString() : "void");
        operateLog.setCostTime(costTime);

        // 保存日志
        log.info("记录操作日志：{}", operateLog);
        operateLogMapper.insert(operateLog);

        return result;
    }

    private Integer getCurrentUserId() {
        return CurrentHolder.getCurrentId();
    }
}
